import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import bb_3 from '@/assets/images/become/3.png'
import bb_6 from '@/assets/images/become/6.png'
import ptVip from '@/assets/images/ptVip.png'
import xyVip from '@/assets/images/xyVip.png'
import zzVip from '@/assets/images/zzVip.png'
import gem from '@/assets/images/gem.png'
import gems from '@/assets/images/gems.png'
import Moregem from '@/assets/images/moregems.png'
import visaicon from '@/assets/images/become/visa.png'
import wsd from '@/assets/images/become/wsd.png'
import { request } from '@/api/request'
import { useNavigate, Link } from 'react-router-dom';
import { getDynamicFonts } from '@/utils/fontUtils';
import useIsMobile from '@/hooks/isMoboile';
import { motion, AnimatePresence } from 'framer-motion';


// 价格配置(新版日元产品)--正式 
const PRICE_CONFIG = {
    prelude: {
        stripe_price_id: "price_1RqwHlChGeSzAdpVznjjAzCX", // TODO: 替换为真实Stripe价格ID
        name_en: "Prelude",
        price: "¥1,500",
        tokens: "1,000",
        recommended: false,
        benefits: [
            // "benefits.items.unlimitedChat",
            "benefits.items.imageGeneration",
            "benefits.items.voiceChat",
            "benefits.items.fastResponse",
            "benefits.items.1000Tokens",
            "benefits.items.Chat",
            "benefits.items.Picture",
            "benefits.items.Voice"
        ]
    },
    affinity: {
        stripe_price_id: "price_1RqwIaChGeSzAdpVwZueHrCa", // TODO: 替换为真实Stripe价格ID
        name_en: "Affinity",
        price: "¥3,000",
        tokens: "3,000",
        recommended: true,
        benefits: [
            // "benefits.items.unlimitedChat",
            "benefits.items.imageGeneration",
            "benefits.items.voiceChat",
            "benefits.items.moreFast",
            "benefits.items.3000Tokens",
            "benefits.items.Chat",
            "benefits.items.Picture",
            "benefits.items.Voice"
        ]
    },
    soulmate: {
        stripe_price_id: "price_1RqwJ1ChGeSzAdpVM7PdkPbB", // TODO: 替换为真实Stripe价格ID
        name_en: "Soulmate",
        price: "¥7,200",
        tokens: "9,000",
        recommended: false,
        benefits: [
            // "benefits.items.unlimitedChat",
            "benefits.items.imageGeneration",
            "benefits.items.voiceChat",
            "benefits.items.bestFast",
            "benefits.items.9000Tokens",
            "benefits.items.Chat",
            "benefits.items.Picture",
            "benefits.items.Voice"
        ]
    }
};

// 价格配置(新版日元产品)--测试 
// const PRICE_CONFIG = {
//     prelude: {
//         stripe_price_id: "price_1RiRamEHIcYxLscxdnQiqVg9", // TODO: 替换为真实Stripe价格ID
//         name_en: "Prelude",
//         price: "¥1,500",
//         tokens: "1,000",
//         recommended: false,
//         benefits: [
//             "benefits.items.unlimitedChat",
//             "benefits.items.voiceChat",
//             "benefits.items.imageGeneration",
//             "benefits.items.fastResponse",
//             "benefits.items.1000Tokens"
//         ]
//     },
//     affinity: {
//         stripe_price_id: "price_1RiRccEHIcYxLscxGcX5mDSa", // TODO: 替换为真实Stripe价格ID
//         name_en: "Affinity",
//         price: "¥3,000",
//         tokens: "3,000",
//         recommended: true,
//         benefits: [
//             "benefits.items.unlimitedChat",
//             "benefits.items.imageGeneration",
//             "benefits.items.voiceChat",
//             "benefits.items.moreFast",
//             "benefits.items.3000Tokens"
//         ]
//     },
//     soulmate: {
//         stripe_price_id: "price_1RiRdYEHIcYxLscxXWNVZMu8", // TODO: 替换为真实Stripe价格ID
//         name_en: "Soulmate",
//         price: "¥7,200",
//         tokens: "9,000",
//         recommended: false,
//         benefits: [
//             "benefits.items.unlimitedChat",
//             "benefits.items.imageGeneration",
//             "benefits.items.voiceChat",
//             "benefits.items.bestFast",
//             "benefits.items.9000Tokens"
//         ]
//     }
// };

// 新增倒计时 hook - 优化移动端抖动问题
function useCountdown(initialMs: number) {
    const [timeLeft, setTimeLeft] = useState(initialMs);
    useEffect(() => {
        if (timeLeft <= 0) return;
        // 降低更新频率，减少抖动
        const interval = setInterval(() => {
            setTimeLeft(t => (t > 0 ? t - 100 : 0));
        }, 100);
        return () => clearInterval(interval);
    }, [timeLeft]);
    const minutes = Math.floor(timeLeft / 60000);
    const seconds = Math.floor((timeLeft % 60000) / 1000);
    const ms = Math.floor((timeLeft % 1000) / 100); // 调整为100ms单位
    return { minutes, seconds, ms };
}

const Subscriptions: React.FC = () => {
    const { t, i18n } = useTranslation();
    const dynamicFonts = getDynamicFonts(i18n);
    // 获取用户数据和当前VIP等级
    const [userData, setUserData] = useState<any>(null);
    const [currentVipLevel, setCurrentVipLevel] = useState<number>(0);
    
    // 查找默认推荐的套餐
    const defaultRecommendedPlan = Object.entries(PRICE_CONFIG).find(
        ([_, config]) => config.recommended
    )?.[0] as 'prelude' | 'affinity' | 'soulmate' | undefined || 'affinity';
    
    // 初始化时先设置为推荐套餐，避免闪烁问题
    const [selectedPlan, setSelectedPlan] = useState<'' | 'prelude' | 'affinity' | 'soulmate'>(defaultRecommendedPlan);
    const [isLoading, setIsLoading] = useState(false); // 支付loading状态
    const [hoveredCard, setHoveredCard] = useState<string | null>(null); // 鼠标悬停状态
    const navigate = useNavigate();
    const countdown = useCountdown(30 * 60 * 1000); // 30分钟
    const isMobile = useIsMobile(); // 使用移动端检测hook
    
    // 添加一个状态来控制是否已经完成初始化
    const [initialized, setInitialized] = useState(false);

    // VIP等级与套餐类型的映射
    const vipLevelToPlan: Record<number, 'prelude' | 'affinity' | 'soulmate'> = {
        1: 'prelude',
        2: 'affinity',
        3: 'soulmate'
    };

    // 创建引用来访问推荐产品的容器元素
    const recommendedCardRef = React.useRef<HTMLDivElement>(null);

    // 在组件初始化时获取用户数据和等级
    useEffect(() => {
        // 获取用户数据
        const userDataString = localStorage.getItem('userData');
        if (userDataString) {
            const parsedUserData = JSON.parse(userDataString);
            setUserData(parsedUserData);

            // 获取当前VIP等级
            if (parsedUserData && parsedUserData.vip_live) {
                const vipLevel = parsedUserData.vip_live;
                setCurrentVipLevel(vipLevel);
                
                // 如果用户已经是会员，则选中当前会员等级对应的套餐
                if (vipLevel > 0 && vipLevelToPlan[vipLevel]) {
                    setSelectedPlan(vipLevelToPlan[vipLevel]);
                }
                // 如果用户不是会员，保持默认选中推荐套餐（已在useState中设置）
            }
        }
        
        setInitialized(true); // 标记初始化完成

        // 组件卸载时清除选中状态
        return () => {
            setSelectedPlan('');
        };
    }, []);

    // 添加自动滚动到推荐产品位置的效果
    useEffect(() => {
        // 在移动端，当组件挂载后，滚动到推荐产品位置
        if (isMobile && recommendedCardRef.current) {
            setTimeout(() => {
                recommendedCardRef.current?.scrollIntoView({
                    behavior: 'smooth',
                    block: 'center',
                    inline: 'center'
                });
            }, 500); // 延迟500ms以确保元素已完全渲染
        }
    }, [isMobile]);

    // 处理订阅选项点击
    const handlePlanSelect = (planType: 'prelude' | 'affinity' | 'soulmate') => {
        // 检查是否为当前会员等级
        const userCurrentPlan = currentVipLevel ? vipLevelToPlan[currentVipLevel] : undefined;
        const isCurrentPlan = userCurrentPlan === planType;

        // 判断是否应该禁用（当前等级的产品）
        const shouldDisable = currentVipLevel > 0 && isCurrentPlan;

        // 如果产品被禁用，则不允许选择
        if (shouldDisable) {
            return;
        }

        // 如果点击已选中的选项，则取消选择
        if (selectedPlan === planType) {
            setSelectedPlan('affinity'); // 默认回到推荐套餐
        } else {
            setSelectedPlan(planType);
        }
    };

    // 处理支付按钮点击
    const handlePaymentClick = async (event: React.MouseEvent<HTMLButtonElement>) => {
        event.preventDefault(); // 阻止表单提交

        // 检查是否为当前等级，如果是则不允许支付
        if (!!currentVipLevel && vipLevelToPlan[currentVipLevel] === selectedPlan) {
            return; // 已经拥有此套餐
        }

        // 设置loading状态
        setIsLoading(true);

        try {
            // 获取存储的用户数据
            const userDataString = localStorage.getItem('userData');

            if (!userDataString) {
                alert(t('tokenModal.errors.loginRequired'));
                setIsLoading(false);
                return;
            }

            // 解析用户数据
            const userData = JSON.parse(userDataString);
            const { visitor_uuid, user_email } = userData;

            if (!visitor_uuid || !user_email) {
                alert(t('tokenModal.errors.userDataIncomplete'));
                setIsLoading(false);
                return;
            }

            // 获取选中计划的价格配置
            const selectedPriceConfig = selectedPlan ? PRICE_CONFIG[selectedPlan] : null;
            if (!selectedPriceConfig) {
                alert(t('tokenModal.errors.invalidPlan'));
                setIsLoading(false);
                return;
            }

            // 构造请求参数
            const requestParams = {
                stripe_price_id: selectedPriceConfig.stripe_price_id,
                user_uuid: visitor_uuid,
                email: user_email
            };

            console.log(t('tokenModal.logs.paymentWithPlan') + ':', selectedPlan);

            const res = await request.post('/api/stripe/create-subscription', requestParams);

            if (res.status === 200 && res.data) {
                // console.log('Payment intent created:', res.data);
                // 将支付信息存储到sessionStorage，以便在Pay页面使用
                sessionStorage.setItem('paymentData', JSON.stringify({
                    clientSecret: res.data.clientSecret,
                    amount: res.data.amount,
                    currency: res.data.currency,
                    selectedPlan: selectedPlan,
                    stripe_price_id: selectedPriceConfig.stripe_price_id
                }));

                // 跳转到支付页面
                navigate('/PayMoney');
            } else {
                // console.error('支付请求失败:', res);
                console.error('payment request failed', res);
                alert(t('tokenModal.errors.paymentFailed'));
                setIsLoading(false);
            }
        } catch (error: any) {
            console.error(t('tokenModal.logs.paymentError') + ':', error.response?.data?.message || t('tokenModal.errors.networkError'));
            alert(error.response?.data?.message || t('tokenModal.errors.networkError'));
            setIsLoading(false);
        }
    };

    // 渲染会员卡片
    const renderMembershipCard = (planType: 'prelude' | 'affinity' | 'soulmate') => {
        const config = PRICE_CONFIG[planType];
        const isRecommended = config.recommended;
        const isSelected = selectedPlan === planType;
        const isAffinity = planType === 'affinity';

        // 检查是否为当前会员等级
        const userCurrentPlan = currentVipLevel ? vipLevelToPlan[currentVipLevel] : undefined;
        const isCurrentPlan = userCurrentPlan === planType;

        // 判断是否应该禁用（当前等级的产品）
        const shouldDisable = currentVipLevel > 0 && isCurrentPlan;

        // 只有在初始化完成后才显示选中样式，避免闪烁问题
        const shouldShowSelected = initialized && isSelected;

        const membershipIconMap: Record<string, string> = {
            'prelude': ptVip,
            'affinity': xyVip,
            'soulmate': zzVip
        };

        return (
            <div className={`flex flex-col ${isMobile ? 'w-[85%] min-w-[250px] h-full' : 'w-full'} px-0.5 sm:px-1 md:px-3 ${shouldShowSelected ? 'relative z-10' : ''} relative ${shouldDisable ? 'opacity-50' : ''}`}
                onClick={shouldDisable ? undefined : () => handlePlanSelect(planType)}>
                {/* 会员类型图标 */}
                <div className={`hidden md:block absolute -right-4 lg:-right-8 -top-16 lg:-top-24 w-24 lg:w-36 h-24 lg:h-36 z-20 ${isAffinity || shouldShowSelected ? 'animate-bounce-slow' : ''} ${shouldDisable ? 'grayscale' : ''}`}>
                    <img src={membershipIconMap[planType]} alt="" className="w-full h-full object-contain" />
                </div>

                {/* 当前等级印章 - 日本风格 */}
                <AnimatePresence>
                    {isCurrentPlan && (
                        <motion.div
                            className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-36 h-36 z-30"
                            initial={{ opacity: 0, scale: 0.3, rotate: -15 }}
                            animate={{
                                opacity: 1,
                                scale: 1,
                                rotate: 0,
                                transition: {
                                    type: "spring",
                                    duration: 0.8,
                                    bounce: 0.5,
                                    delay: 0.2
                                }
                            }}
                            exit={{ opacity: 0, scale: 0.5, transition: { duration: 0.3 } }}
                        >
                            <motion.div
                                className="relative w-full h-full"
                                whileHover={{ scale: 1.05, rotate: 5 }}
                                transition={{ type: "spring", stiffness: 300, damping: 10 }}
                            >
                                {/* 基础红色圆底 - 日本風印鑑 */}
                                <motion.div
                                    className="absolute inset-0 w-full h-full rounded-full bg-gradient-to-br from-red-700 to-red-500 opacity-80 shadow-lg"
                                    initial={{ boxShadow: "0 0 0 rgba(185, 28, 28, 0)" }}
                                    animate={{
                                        boxShadow: "0 0 20px rgba(185, 28, 28, 0.5)",
                                        transition: { duration: 1, repeat: Infinity, repeatType: "reverse" }
                                    }}
                                ></motion.div>

                                {/* 印章特效 - 纹理效果 */}
                                <motion.div
                                    className="absolute inset-0 w-full h-full rounded-full bg-red-600 mix-blend-overlay opacity-30"
                                    style={{ backgroundImage: 'radial-gradient(circle, transparent 30%, rgba(0,0,0,0.3) 70%)' }}
                                ></motion.div>

                                {/* 传统印章外圈线条装饰 - 固定不旋转 */}
                                <div className="absolute inset-0 w-full h-full rounded-full border-2 border-red-300 opacity-20"></div>

                                {/* 传统印章内圈线条装饰 - 旋转效果 */}
                                <motion.div
                                    className="absolute inset-0 w-[92%] h-[92%] m-auto rounded-full border border-red-300 opacity-40"
                                    animate={{ rotate: 360 }}
                                    transition={{ duration: 20, repeat: Infinity, ease: "linear" }}
                                ></motion.div>
                                <motion.div
                                    className="absolute inset-0 w-[84%] h-[84%] m-auto rounded-full border border-red-300 opacity-30"
                                    animate={{ rotate: -360 }}
                                    transition={{ duration: 25, repeat: Infinity, ease: "linear" }}
                                ></motion.div>

                                {/* 内圈白色文字区域 */}
                                <motion.div
                                    className="absolute inset-0 m-auto w-[70%] h-[70%] flex items-center justify-center rounded-full border-2 border-red-300 bg-red-600/20"
                                    animate={{ rotate: [0, 2, 0, -2, 0] }}
                                    transition={{ duration: 5, repeat: Infinity, ease: "linear" }}
                                >
                                    <motion.div
                                        style={{ fontFamily: dynamicFonts.font4 }}
                                        className="text-white text-base md:text-lg lg:text-xl font-bold whitespace-nowrap tracking-wider"
                                        animate={{ scale: [1, 1.05, 1] }}
                                        transition={{ duration: 2, repeat: Infinity, ease: "easeInOut" }}
                                    >
                                        {t('subscription.currentPlan')}
                                    </motion.div>
                                </motion.div>
                            </motion.div>
                        </motion.div>
                    )}
                </AnimatePresence>

                {/* 最外层的卡片盒子 */}
                <motion.div
                    className={`rounded-lg ${shouldShowSelected ? 'gradient-border-card' : ''} ${shouldDisable ? 'grayscale cursor-not-allowed' : ''}`}
                    initial={{ opacity: 0.8 }}
                    animate={{
                        opacity: 1,
                        scale: shouldShowSelected ? 1.05 : 1,
                        y: shouldShowSelected ? -5 : 0
                    }}
                    whileHover={!shouldDisable ? {
                        scale: 1.05,
                        y: -5,
                        transition: { type: "spring", stiffness: 400, damping: 10 }
                    } : {}}
                    transition={{ duration: 0.3 }}
                >
                    {/* 头部 */}
                    <motion.div
                        className={`p-2 sm:p-3 md:p-5 rounded-t-lg text-center ${shouldDisable
                            ? 'bg-gray-600 cursor-not-allowed'
                            : shouldShowSelected
                                ? 'bg-gradient-to-r from-[rgb(225,32,78)] to-[rgb(252,118,138)] shadow-lg shadow-[rgb(225,32,78)]/20 relative z-10 cursor-pointer'
                                : 'bg-zinc-800 hover:bg-zinc-700 cursor-pointer'
                            } ${shouldShowSelected ? 'relative' : ''}`}
                        whileHover={!shouldDisable && !shouldShowSelected ? {
                            backgroundColor: "rgb(63,63,70)",
                        } : {}}
                        transition={{ duration: 0.2 }}
                    >
                        {/* 标题 */}
                        <motion.h3
                            style={{ fontFamily: dynamicFonts.font4 }}
                            className="text-xs sm:text-sm md:text-xl lg:text-[1.8rem] font-bold text-white mb-0.5 sm:mb-1 md:mb-2 whitespace-nowrap"
                            animate={shouldShowSelected ? {
                                scale: [1, 1.05, 1],
                                textShadow: ["0 0 0px rgba(255,255,255,0)", "0 0 8px rgba(255,255,255,0.5)", "0 0 0px rgba(255,255,255,0)"]
                            } : {}}
                            transition={{ duration: 2, repeat: shouldShowSelected ? Infinity : 0, repeatDelay: 3 }}
                        >
                            {t(`subscription.packages.names.${planType}`)}
                        </motion.h3>
                        {/* 价格 */}
                        <motion.p
                            style={{ fontFamily: dynamicFonts.font4 }}
                            className="text-sm sm:text-base md:text-xl lg:text-[2rem] pt-1 sm:pt-2 text-gray-200 font-bold"
                            animate={shouldShowSelected ? { y: [0, -2, 0] } : {}}
                            transition={{ duration: 1.5, repeat: shouldShowSelected ? Infinity : 0, repeatDelay: 1 }}
                        >
                            {config.price}/{t('subscription.time')}
                        </motion.p>
                    </motion.div>

                    {/* Token赠送区域 - 醒目提示 */}
                    <motion.div
                        className="p-1 xs:p-1.5 sm:p-2 md:p-4 border-l border-r border-zinc-700 bg-zinc-900"
                        animate={shouldShowSelected ? {
                            backgroundColor: ["rgb(24,24,27)", "rgb(39,39,42)", "rgb(24,24,27)"]
                        } : {}}
                        transition={{ duration: 3, repeat: shouldShowSelected ? Infinity : 0 }}
                    >
                        <motion.div
                            className={`flex justify-center items-center p-1.5 xs:p-2 sm:p-3 md:p-4 rounded-lg ${shouldShowSelected ? 'bg-gradient-to-r from-[#2A1B44] via-[#55242F] to-[#2A1B44]' : 'bg-gradient-to-r from-[#2A1B44]/70 via-[#55242F]/70 to-[#2A1B44]/70'}`}
                            whileHover={{ scale: 1.02 }}
                            animate={shouldShowSelected ? {
                                boxShadow: ["0 0 0px rgba(225,32,78,0)", "0 0 10px rgba(225,32,78,0.3)", "0 0 0px rgba(225,32,78,0)"]
                            } : {}}
                            transition={{ duration: 2, repeat: shouldShowSelected ? Infinity : 0 }}
                        >
                            {/* 标签展示赠送余额 - 单行设计 */}
                            <div
                                style={{ fontFamily: dynamicFonts.font3 }}
                                className={`text-white ml-1 sm:ml-1.5 px-2 xs:px-3 sm:px-4 md:px-5 py-1 sm:py-1.5 ${shouldShowSelected ? 'bg-[rgba(255,55,95,0.15)]' : 'bg-[rgba(255,55,95,0.1)]'} rounded-full font-medium flex items-center whitespace-nowrap flex-1 justify-center`}
                            >
                                <div className="flex-shrink-0 flex items-center justify-center ">
                                    <img
                                        src={planType === 'prelude' ? gem : planType === 'affinity' ? gems : Moregem}
                                        className="w-4 h-4 xs:w-5 xs:h-5 sm:w-6 sm:h-6 md:w-[1.5rem] md:h-[1.5rem] lg:w-7 lg:h-7"
                                        alt="token"
                                        style={{
                                            width:'3.5rem',
                                            height:"3.5rem",
                                            maxWidth: '100%',
                                            maxHeight: '100%'
                                        }}
                                    />
                                </div>
                                {(() => {
                                    // 获取当前语言
                                    const currentLang = i18n.language;
                                    // 根据不同语言定义格式 - 单行模式
                                    const formats: Record<string, JSX.Element> = {
                                        'zh': <div className="flex items-center">
                                            <motion.span
                                                className="text-[10px] xs:text-xs sm:text-sm"
                                                animate={shouldShowSelected ? { opacity: [0.8, 1, 0.8] } : {}}
                                                transition={{ duration: 2, repeat: shouldShowSelected ? Infinity : 0 }}
                                            >赠送</motion.span>
                                            <motion.span
                                                style={{
                                                    fontFamily: dynamicFonts.font4,
                                                    fontWeight: 900,
                                                    color: 'white',
                                                    textShadow: '0 2px 4px rgba(255,55,95,0.2)'
                                                }}
                                                className="mx-1 text-base xs:text-lg sm:text-xl md:text-2xl lg:text-3xl"
                                                whileHover={{ scale: 1.1 }}
                                                animate={shouldShowSelected ? {
                                                    textShadow: ["0 2px 4px rgba(255,55,95,0.2)", "0 2px 12px rgba(255,55,95,0.6)", "0 2px 4px rgba(255,55,95,0.2)"],
                                                    scale: [1, 1.05, 1]
                                                } : {}}
                                                transition={{ duration: 1.5, repeat: shouldShowSelected ? Infinity : 0, repeatDelay: 1 }}
                                            >{config.tokens}</motion.span>
                                            <motion.span
                                                className="text-[10px] xs:text-xs sm:text-sm"
                                                animate={shouldShowSelected ? { opacity: [0.8, 1, 0.8] } : {}}
                                                transition={{ duration: 2, repeat: shouldShowSelected ? Infinity : 0 }}
                                            >代币</motion.span>
                                        </div>,
                                        // 日语 
                                        'ja': <div className="flex items-center">
                                            <motion.span
                                                style={{
                                                    fontFamily: dynamicFonts.font4,
                                                    fontWeight: 900,
                                                    color: 'white',
                                                    textShadow: '0 2px 4px rgba(255,55,95,0.2)'
                                                }}
                                                className="mx-1 text-base xs:text-lg sm:text-xl md:text-2xl lg:text-3xl"
                                                whileHover={{ scale: 1.1 }}
                                                animate={shouldShowSelected ? {
                                                    textShadow: ["0 2px 4px rgba(255,55,95,0.2)", "0 2px 12px rgba(255,55,95,0.6)", "0 2px 4px rgba(255,55,95,0.2)"],
                                                    scale: [1, 1.05, 1]
                                                } : {}}
                                                transition={{ duration: 1.5, repeat: shouldShowSelected ? Infinity : 0, repeatDelay: 1 }}
                                            >{config.tokens}</motion.span>
                                            <motion.span
                                                className="text-[10px] xs:text-xs sm:text-sm"
                                                animate={shouldShowSelected ? { opacity: [0.8, 1, 0.8] } : {}}
                                                transition={{ duration: 2, repeat: shouldShowSelected ? Infinity : 0 }}
                                            >ジェムをギフト</motion.span>
                                        </div>,
                                        // 英语 
                                        'en': <div className="flex items-center">
                                            <motion.span
                                                className="text-[10px] xs:text-xs sm:text-sm"
                                                animate={shouldShowSelected ? { opacity: [0.8, 1, 0.8] } : {}}
                                                transition={{ duration: 2, repeat: shouldShowSelected ? Infinity : 0 }}
                                            >Gift</motion.span>
                                            <motion.span
                                                style={{
                                                    fontFamily: dynamicFonts.font4,
                                                    fontWeight: 900,
                                                    color: 'white',
                                                    textShadow: '0 2px 4px rgba(255,55,95,0.2)'
                                                }}
                                                className="mx-1 text-base xs:text-lg sm:text-xl md:text-2xl lg:text-3xl"
                                                whileHover={{ scale: 1.1 }}
                                                animate={shouldShowSelected ? {
                                                    textShadow: ["0 2px 4px rgba(255,55,95,0.2)", "0 2px 12px rgba(255,55,95,0.6)", "0 2px 4px rgba(255,55,95,0.2)"],
                                                    scale: [1, 1.05, 1]
                                                } : {}}
                                                transition={{ duration: 1.5, repeat: shouldShowSelected ? Infinity : 0, repeatDelay: 1 }}
                                            >{config.tokens}</motion.span>
                                            <motion.span
                                                className="text-[10px] xs:text-xs sm:text-sm"
                                                animate={shouldShowSelected ? { opacity: [0.8, 1, 0.8] } : {}}
                                                transition={{ duration: 2, repeat: shouldShowSelected ? Infinity : 0 }}
                                            >tokens</motion.span>
                                        </div>
                                    };

                                    // 返回当前语言的格式，如果没有则使用英文作为默认值
                                    return formats[currentLang] || formats['en'];
                                })()}
                            </div>
                        </motion.div>
                    </motion.div>

                    {/* 会员权益 */}
                    <motion.div
                        className="p-2 sm:p-3 md:p-5 border-l border-r border-b border-zinc-700 bg-zinc-900"
                        animate={shouldShowSelected ? {
                            backgroundColor: ["rgb(24,24,27)", "rgb(28,28,31)", "rgb(24,24,27)"]
                        } : {}}
                        transition={{ duration: 4, repeat: shouldShowSelected ? Infinity : 0 }}
                    >
                        <ul className="text-xs sm:text-sm text-gray-300 space-y-1 sm:space-y-2 md:space-y-3 relative z-10">
                            {config.benefits.map((benefitKey, index) => (
                                <motion.li
                                    key={index}
                                    className="flex items-start sm:items-center"
                                    initial={{ opacity: 0, x: -5 }}
                                    animate={{ opacity: 1, x: 0 }}
                                    transition={{ delay: index * 0.1, duration: 0.3 }}
                                    whileHover={{ x: 3 }}
                                >
                                    <motion.span
                                        className={`mr-1 sm:mr-2 text-sm sm:text-base md:text-lg flex-shrink-0 ${shouldShowSelected ? 'text-rose-400' : 'text-green-400'}`}
                                        animate={shouldShowSelected ? { scale: [1, 1.2, 1] } : {}}
                                        transition={{ duration: 1.5, delay: index * 0.2, repeat: shouldShowSelected ? Infinity : 0, repeatDelay: 3 }}
                                    >✓</motion.span>
                                    <motion.span
                                        style={{ fontFamily: dynamicFonts.font3 }}
                                        className="text-xs sm:text-sm md:text-base leading-tight sm:leading-normal"
                                        animate={shouldShowSelected ? { color: ["rgb(209,213,219)", "rgb(229,231,235)", "rgb(209,213,219)"] } : {}}
                                        transition={{ duration: 2, delay: index * 0.1, repeat: shouldShowSelected ? Infinity : 0, repeatDelay: 2 }}
                                    >
                                        {t(`subscription.${benefitKey}`)}
                                    </motion.span>
                                </motion.li>
                            ))}
                        </ul>

                        {/* 产品介绍 */}
                        {/* <div className="mt-3 md:mt-4 pt-2 md:pt-3 border-t border-zinc-700">
                            <div style={{ fontFamily: dynamicFonts.font1 }} className="text-neutral-400 text-xs md:text-sm font-normal break-words leading-relaxed">
                                {t(`subscription.productIntro.${planType}`)}
                            </div>
                        </div> */}
                    </motion.div>
                </motion.div>

                {/* 热门选择标签 - 只在affinity套餐上显示 */}
                {isAffinity && (
                    <>
                        <div style={{ fontFamily: dynamicFonts.font4 }} className="absolute top-[-0.75rem] left-0.5 sm:left-1 md:left-2 w-max px-1.5 sm:px-2 md:px-4 py-0.5 sm:py-1 bg-gradient-to-r from-[rgb(225,32,78)] to-[rgb(252,118,138)] text-white text-[10px] sm:text-xs md:text-sm lg:text-base font-bold rounded-full shadow-md shadow-[rgb(225,32,78)]/20 z-20">
                            {t('buyToken.popularChoice')}
                        </div>
                        {/* 添加星星装饰 */}
                        <div className="absolute -top-2 -left-2 w-2 h-2 sm:w-3 sm:h-3 md:w-4 md:h-4 text-yellow-400 animate-ping opacity-75">✦</div>
                        <div className="absolute -bottom-2 -right-2 w-2 h-2 sm:w-3 sm:h-3 md:w-4 md:h-4 text-yellow-400 animate-ping opacity-75 delay-300">✦</div>
                    </>
                )}
            </div>
        );
    };

    // 自定义动画样式
    const customStyles = `
    @keyframes bounce-slow {
        0%, 100% {
            transform: translateY(0);
        }
        50% {
            transform: translateY(-10px);
        }
    }
    .animate-bounce-slow {
        animation: bounce-slow 3s ease-in-out infinite;
    }
    
    @keyframes gradient-animation {
        0% {
            background-position: 0% 50%;
        }
        50% {
            background-position: 100% 50%;
        }
        100% {
            background-position: 0% 50%;
        }
    }
    
    .gradient-border-card {
        position: relative;
        border-radius: 0.5rem;
    }
    
    .gradient-border-card::before {
        content: "";
        position: absolute;
        inset: 0;
        padding: 2px;
        border-radius: 0.5rem;
        background: linear-gradient(
            to right,
            rgb(225, 32, 78),
            rgb(252, 118, 138),
            rgb(225, 32, 78)
        );
        background-size: 200% 200%;
        animation: gradient-animation 3s ease infinite;
        -webkit-mask: 
            linear-gradient(#fff 0 0) content-box, 
            linear-gradient(#fff 0 0);
        -webkit-mask-composite: xor;
        mask-composite: exclude;
        pointer-events: none;
        z-index: 10;
    }

    .mobile-card-container {
        overflow-x: auto;
        overflow-y: hidden; /* 禁止垂直滚动 */
        -webkit-overflow-scrolling: touch;
        scrollbar-width: none; /* Firefox */
        -ms-overflow-style: none; /* IE and Edge */
        scroll-snap-type: x mandatory;
        padding-bottom: 15px;
        min-height: 20rem; /* 调整容器高度 */
        display: flex;
        align-items: center; /* 垂直居中对齐 */
    }
    
    .mobile-card-container::-webkit-scrollbar {
        display: none; /* Chrome, Safari, Opera */
    }
    
    .mobile-card-item {
        scroll-snap-align: center;
        height: 100%;
        display: flex;
        align-items: center;
    }
    
    /* 日本风格印章效果 */
    @keyframes stamp-appear {
        0% {
            opacity: 0;
            transform: scale(0.3);
        }
        30% {
            opacity: 0.8;
            transform: scale(1.2);
        }
        60% {
            opacity: 0.9;
            transform: scale(0.95);
        }
        80% {
            transform: scale(1.05);
        }
        100% {
            opacity: 1;
            transform: scale(1);
        }
    }
    
    .stamp-animation {
        animation: stamp-appear 0.7s ease-out forwards;
    }
    `;

    return (
        <div style={{ width: '100%' }} className=" bg-app-dark text-white flex w-full min-w-0 flex-col">
            {/* 自定义动画样式 */}
            <style dangerouslySetInnerHTML={{ __html: customStyles }} />

            {/* 侧边栏和主内容区 */}
            <div className="flex w-full min-w-0 flex-1 ">
                {/* 右侧主内容区  */}
                <div className="flex-1 w-full ">

                    {/* 广告一  */}
                    {/* <Link to="/become-premium">
                        <div style={{ fontFamily: dynamicFonts.font4 }} className="flex relative w-full cursor-pointer bg-gradient-to-r from-[#2A1B44] via-[#55242F] to-[#2A1B44]" data-banner-component-target="track" data-banner-component-mixpanel-value="false" data-banner-component-mixpanel-data-value="">
                            <div className="flex w-full justify-between items-center h-[56px] overflow-hidden">
                                <div className="flex w-full justify-center items-center px-4 md:px-6 min-w-0">
                                    <div className="hidden md:flex leading-normal text-white text-[24px] font-black uppercase mr-4">
                                        {t('subscription.firstPurchase')}
                                    </div>
                                    <div className="flex items-center gap-2 md:gap-4 flex-shrink-0">
                                        <img className="w-[34px] md:w-[50px] flex-shrink-0" src={deamo} alt="diamond" />
                                        <div className="leading-5 text-white text-sm md:text-[24px] font-black uppercase mr-2 md:mr-6 whitespace-nowrap">
                                            {t('subscription.upTo70Off')}
                                        </div>
                                    </div>
                                    倒计时区域 - 优化移动端布局稳定性
                                    <div style={{ fontFamily: dynamicFonts.font2 }} className="flex-shrink-0 min-w-[120px] sm:min-w-[160px] md:min-w-[180px]">
                                        <div className="flex justify-center items-center gap-0.5 md:gap-1 ml-0 md:ml-6">
                                            分钟
                                            <div className="flex items-center gap-0.5 min-w-0">
                                                <div className="text-white text-xs sm:text-sm md:text-base font-bold leading-none font-mono min-w-[1.1em] sm:min-w-[1.2em] text-center">
                                                    {String(countdown.minutes).padStart(2, '0')}
                                                </div>
                                                <div className="text-[#8d616b] text-xs font-normal leading-none whitespace-nowrap">
                                                    {t('subscription.countdownLabels.min')}
                                                </div>
                                            </div>

                                            分隔符
                                            <div className="text-[#8d616b] text-xs sm:text-sm font-bold mx-0.5">:</div>

                                            秒钟
                                            <div className="flex items-center gap-0.5 min-w-0">
                                                <div className="text-white text-xs sm:text-sm md:text-base font-bold leading-none font-mono min-w-[1.1em] sm:min-w-[1.2em] text-center">
                                                    {String(countdown.seconds).padStart(2, '0')}
                                                </div>
                                                <div className="text-[#8d616b] text-xs font-normal leading-none whitespace-nowrap">
                                                    {t('subscription.countdownLabels.sec')}
                                                </div>
                                            </div>

                                            分隔符 - 在小屏幕上隐藏
                                            <div className="text-[#8d616b] text-xs sm:text-sm font-bold mx-0.5 hidden sm:block">:</div>

                                            毫秒 - 在小屏幕上隐藏
                                            <div className="items-center gap-0.5 min-w-0 hidden sm:flex">
                                                <div className="text-white text-xs sm:text-sm md:text-base font-bold leading-none font-mono min-w-[1.1em] sm:min-w-[1.2em] text-center">
                                                    {String(countdown.ms).padStart(2, '0')}
                                                </div>
                                                <div className="text-[#8d616b] text-xs font-normal leading-none whitespace-nowrap">
                                                    {t('subscription.countdownLabels.ms')}
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div className="absolute bottom-0 left-0 w-full h-[2px] bg-[linear-gradient(270deg,_#5505E6_0%,_#F76E85_48.5%,_#5505E6_100%)]"></div>
                        </div>
                    </Link> */}

                    {/* 标题一  */}
                    <div style={{ fontFamily: dynamicFonts.font4 }} className="relative flex flex-col justify-center items-center gap-2 md:gap-4 px-6 pt-4 pb-1 md:pb-2 pr-5">
                        <div className="block text-center text-white text-xl lg:text-3xl font-semibold ">
                            {t('subscription.title')}
                        </div>
                        {/* PC端副标题 */}
                        {/* <div style={{ fontFamily: dynamicFonts.font3 }} className="text-neutral-400 text-sm md:text-base font-normal leading-tight hidden md:block">
                            {t('subscription.anonymousCancel')}
                        </div> */}
                        {/* 移动端副标题 */}
                        {/* <div className="text-white text-center text-sm md:hidden">
                            {t('subscription.upToOffForFirst', { percent: 70 })}
                        </div> */}
                    </div>

                    {/* 左侧装饰图 */}
                    {/* <div className="absolute bottom-0 left-[-3rem] w-40 h-40 md:w-64 md:h-64 pointer-events-none z-0 overflow-hidden hidden md:block opacity-70">
                        <img src={girl_left} alt="" className="w-full h-full object-contain" />
                    </div> */}

                    {/* 会员卡片区域 */}
                    <div className={`${isMobile ? 'w-[95vw] py-0' : 'w-[98%] md:w-[95%] 2xl:w-[70%] py-4 md:py-6'} max-w-full mx-auto relative bg-transparent md:bg-zinc-900 rounded-lg border border-zinc-800 isolate mt-2 flex flex-col px-2 md:px-5`}>
                        {/* 根据设备类型选择布局 */}
                        {isMobile ? (
                            // 移动端布局 - 横向滚动布局
                            <div className="mobile-card-container flex gap-3 mb-6 md:mb-8 max-w-full">
                                <div className="mobile-card-item flex-shrink-0 mt-4">
                                    {renderMembershipCard('prelude')}
                                </div>
                                <div
                                    className="mobile-card-item flex-shrink-0 mt-4"
                                    ref={PRICE_CONFIG['affinity'].recommended ? recommendedCardRef : null}
                                >
                                    {renderMembershipCard('affinity')}
                                </div>
                                <div className="mobile-card-item flex-shrink-0 mt-4">
                                    {renderMembershipCard('soulmate')}
                                </div>
                            </div>
                        ) : (
                            // PC端布局 - 网格布局
                            <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 sm:gap-1 md:gap-2 lg:gap-3 mb-6 md:mb-8 max-w-full">
                                {renderMembershipCard('prelude')}
                                {renderMembershipCard('affinity')}
                                {renderMembershipCard('soulmate')}
                            </div>
                        )}

                        {/* 支付按钮 */}
                        <div className="max-w-md mx-auto w-full">
                            <motion.button
                                style={{ fontFamily: dynamicFonts.font3 }}
                                className={`w-full px-4 py-3 md:py-4 rounded-lg flex justify-center items-center gap-2 md:gap-3 mb-3 ${isLoading || (!!currentVipLevel && vipLevelToPlan[currentVipLevel] === selectedPlan)
                                    ? 'bg-gray-500 cursor-not-allowed opacity-70'
                                    : 'bg-gradient-to-r from-rose-600 to-pink-500 shadow-lg'
                                    }`}
                                onClick={handlePaymentClick}
                                disabled={isLoading || (!!currentVipLevel && vipLevelToPlan[currentVipLevel] === selectedPlan)}
                                title={(!!currentVipLevel && vipLevelToPlan[currentVipLevel] === selectedPlan) ? t('subscription.alreadyOwned') : ''}
                                whileHover={!(isLoading || (!!currentVipLevel && vipLevelToPlan[currentVipLevel] === selectedPlan)) ? {
                                    scale: 1.02,
                                    boxShadow: "0 10px 15px -3px rgba(225, 29, 72, 0.3)",
                                    backgroundImage: "linear-gradient(to right, rgb(190, 18, 60), rgb(219, 39, 119))"
                                } : {}}
                                whileTap={!(isLoading || (!!currentVipLevel && vipLevelToPlan[currentVipLevel] === selectedPlan)) ? {
                                    scale: 0.98
                                } : {}}
                                animate={!(isLoading || (!!currentVipLevel && vipLevelToPlan[currentVipLevel] === selectedPlan)) ? {
                                    boxShadow: ["0 4px 6px -1px rgba(225, 29, 72, 0.1)", "0 8px 10px -2px rgba(225, 29, 72, 0.2)", "0 4px 6px -1px rgba(225, 29, 72, 0.1)"]
                                } : {}}
                                transition={{ duration: 2, repeat: Infinity }}
                            >
                                {isLoading ? (
                                    <>
                                        <div className="animate-spin rounded-full h-5 w-5 md:h-6 md:w-6 border-b-2 border-white"></div>
                                        <div className="text-white text-xs md:text-base font-medium">
                                            {t('buyToken.processing')}
                                        </div>
                                    </>
                                ) : !!currentVipLevel && vipLevelToPlan[currentVipLevel] === selectedPlan ? (
                                    <div style={{ fontFamily: dynamicFonts.font4 }} className="flex items-center justify-center text-white text-base md:text-lg font-bold">
                                        {t('subscription.currentPlan')}
                                    </div>
                                ) : (
                                    <>
                                        <div className="text-white text-[1.5rem]">
                                            {/* {t('subscription.paymentButtons.creditCard')}  */}
                                            {selectedPlan ? PRICE_CONFIG[selectedPlan].price : ''}
                                        </div>
                                        <div className="flex gap-1 md:gap-2">
                                            <img src={visaicon} className="w-[32px] h-5 md:w-[40px] md:h-6 rounded-[5px]" alt="visa" />
                                            <img src={wsd} className="w-[32px] h-5 md:w-[40px] md:h-6 rounded-[5px]" alt="mastercard" />
                                        </div>
                                    </>
                                )}
                            </motion.button>
                        </div>

                        {/* 安全提示 */}
                        <div style={{ fontFamily: dynamicFonts.font4 }} className="mt-4 md:mt-6 text-center">
                            <div className="flex justify-center items-center gap-2 mb-2">
                                <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 md:h-5 md:w-5 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
                                </svg>
                                <p className="text-xs md:text-sm text-gray-300">{t('buyToken.securityInfo')}</p>
                            </div>
                            <p className="text-[10px] md:text-xs text-gray-500">{t('buyToken.termsAgreement')}</p>
                        </div>
                    </div>

                    {/* 底部展示  */}
                    <div className="flex justify-center mt-4 md:mt-6 mb-0 lg:mb-6 lg:pl-[99.43px] px-4">
                        <div className="w-auto flex justify-between">
                            {/* 第一个  */}
                            <div className="flex items-center gap-1 md:gap-2 mr-4 md:mr-6">
                                <img src={bb_3} className="w-6 h-6 sm:w-8 sm:h-8" alt="Antivirus" />
                                <div style={{ fontFamily: dynamicFonts.font3 }} className="text-neutral-400 text-xs sm:text-sm font-semibold leading-none">
                                    {t('subscription.security.antivirus')}
                                </div>
                            </div>
                            {/* 第二个  */}
                            <div className="flex items-center gap-1 md:gap-2">
                                <img src={bb_6} className="w-6 h-6 sm:w-8 sm:h-8" alt="Privacy" />
                                <div style={{ fontFamily: dynamicFonts.font3 }} className="text-neutral-400 text-xs sm:text-sm font-semibold leading-none">
                                    {t('subscription.security.privacy')}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Subscriptions;